package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.MinIOProperties;
import com.heima.common.minio.MinIOService;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import freemarker.template.Configuration;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleHtmlTasks {

    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IApArticleService apArticleService;
    @Autowired
    private MinIOProperties minIOProperties;
    @Autowired
    private Configuration configuration;

    @Async
    public void createHtml(ApArticle apArticle, String content){
        try{
            Long articleId = apArticle.getId();
            //获取数据
            List<Map> mapList = JSON.parseArray(content, Map.class);
            Map map = new HashMap();
            map.put("content",mapList);
            //获取模板
            Template template = configuration.getTemplate("article.ftl");
            //数据和模板结合生成html
            StringWriter writer = new StringWriter();
            template.process(map,writer);
            //把html放到minIo中
            ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            minIOService.upload("/article/"+articleId+".html",inputStream,"text/html");
            String staticUrl = minIOProperties.getEndpoint()+"/"+minIOProperties.getBucketName()+"/article/"+articleId+".html";
            apArticle.setStaticUrl(staticUrl);
            apArticleService.updateById(apArticle);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
